package com.credithc.signature.job.workshop;

import com.credithc.signature.common.constant.CacheConstant;
import com.credithc.signature.common.po.ErrorFilter;
import com.credithc.signature.common.po.SignatureLog;
import com.credithc.signature.common.po.SignatureLogExt;
import com.credithc.signature.common.ro.core.CoreRequet;
import com.credithc.signature.common.utils.CacheUtil;
import com.credithc.signature.common.utils.DateUtil;
import com.credithc.signature.job.constant.MQConstant;
import com.credithc.signature.job.constant.SignStatus;
import com.credithc.signature.job.mq.JobMQSender;
import com.credithc.signature.job.po.Task;
import com.credithc.signature.job.service.InfoService;
import com.credithc.signature.job.utils.ProtobufUtil;
import com.credithc.signature.job.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageBuilder;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
public class SignatureWorker extends AbstractWorker {

    /**
     * 具体执行任务的工人
     *
     * @param task
     * @return
     */
    @Override
    public Object handle(Task task) {
        String threadName = new StringBuilder().append(task.getName()).append("-线程-").append(task.getTaskId()).toString();
        Thread.currentThread().setName(threadName);

        Object result = null;
        if (Objects.isNull(task)) {
            return 0;
        }
        try {
            log.debug("执行任务ID: {} | 执行任务名称: {} | start execute job......", task.getTaskId(), task.getName());
            InfoService infoService = SpringUtil.getBean(InfoService.class);
            List<SignatureLog> signatureLogs = infoService.selectInfoByTaskId(task.getTaskId(), task.getTotal(), task.getStartTime(), task.getEndTime(), task.getChannelNo(), task.getStatusList());
            task.setValue(signatureLogs.size());
            for (SignatureLog signatureLog : signatureLogs) {
                // 过滤不需要重签的数据
                boolean needSend = UnwantedData(signatureLog);

                // 发送MQ
                if (needSend) {
                    sendMqMessage(signatureLog);
                }
            }
            log.debug("执行任务ID: {} | 执行任务名称: {} | end execute job......", task.getTaskId(), task.getName());
            result = task.getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 过滤不需要重签的数据
     *
     * @param signatureLog
     * @return
     */
    private boolean UnwantedData(SignatureLog signatureLog) {
        String signResult = signatureLog.getSignResult();
        String requestSn = signatureLog.getRequestSn();
        Integer signStatus = signatureLog.getSignStatus();
        Date createTime = signatureLog.getCreateTime();
        long interval = DateUtil.betweenNowMinute(createTime);
        boolean needSend = true;
        switch (signStatus) {
            case 0:
                // 判断未处理的任务的时长是否超过固定时间,如果时长小于1分钟，说明刚请求不需要处理
                if (interval < 1) {
                    log.info("请求流水号为：[{}] 的数据不需要重签，数据状态为：[{}],因为请求时长小于1分钟！", requestSn, SignStatus.UNHANDLE.getValue());
                    needSend = false;
                }
                break;
            case 1:
                // 判断处理中的任务的时长是否超过固定时间,如果时长小于2分钟，说明刚请求不需要处理
                if (interval < 2) {
                    log.info("请求流水号为：[{}] 的数据不需要重签，数据状态为：[{}],因为请求时长小于2分钟！", requestSn, SignStatus.PROCESSING.getValue());
                    needSend = false;
                }
                break;
            case 3:
                try {
                    // 过滤错误表中数据
                    List<ErrorFilter> errorFilters = CacheUtil.getErrorFilterLoadingCache().get(CacheConstant.ERROR_MSG_PREFIX);
                    for (ErrorFilter e : errorFilters) {
                        if (signResult.contains(e.getError())) {
                            needSend = false;
                        }
                    }
                    if (!needSend) {
                        log.info("请求流水号为：[{}] 的数据不需要重签，数据状态为：[{}],请查看过滤表中不需要重签的情况！", requestSn, SignStatus.FAILURE.getValue());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                needSend = true;
        }
        return needSend;
    }

    /**
     * 发送MQ消息
     *
     * @param signatureLog
     */
    private void sendMqMessage(SignatureLog signatureLog) {
        // 判断请求是否是新签章类型
        InfoService infoService = SpringUtil.getBean(InfoService.class);
        Long refId = signatureLog.getRefId();
        Date createTime = DateUtil.getNowDate();
        SignatureLogExt logExt = infoService.selectInfoByRefId(refId, createTime);
        String requestData = logExt.getRequestData();
        // 发送MQ
        CoreRequet coreRequet = new CoreRequet(signatureLog.getRequestSn(), signatureLog.getTemplateNo(), signatureLog.getChannelNo(), signatureLog.getIsSeal(), signatureLog.getCallbackUrl(), requestData, true);
        JobMQSender rabbitSender = (JobMQSender) SpringUtil.getBean(MQConstant.RABBITSENDER_NAME);
        byte[] objectBytes = ProtobufUtil.serializer(coreRequet);
        rabbitSender.sendSync(MessageBuilder.withBody(objectBytes).build());
    }

}
